<script setup>
import { deepClone } from '@/utils/index.js'
import dayjs from 'dayjs'
import { onMounted, ref } from 'vue'

const props = defineProps({
  columns: {
    type: Array,
    default: () => [
      {
        type: 'input', // 如type为'date'，可另外接收dateType属性作为日期选择器类型:'date'|'week|'month'|'year'|'dates'(日期多选)
        label: '标题',
        name: 'keyword',
        placeholder: '请输入关键字',
        hidden: false,
      },
    ],
  },
  initData: { // 搜索表单初始值
    type: Object,
    default: () => {
      return {}
    },
  },
  isResetButton: { // 是否显示重置按钮
    type: Boolean,
    default: true,
  },
  loading: {
    type: Boolean,
    default: false,
  },
  onFinish: { // 父组件搜索事件
    type: Function,
    default: () => {},
  },
  labelWidth: {
    type: [String, Number],
    default: '85px',
  },
})
const emit = defineEmits(['search', 'reset'])
const formValues = ref({})
const formRef = ref()
onMounted(() => {
  formValues.value = deepClone(props.initData);
})

function searchForm(formEl) {
  if (!formEl) {
    return
  }
  const fields = JSON.parse(JSON.stringify(formValues.value))
  props.columns.forEach((item) => {
    if (item.type === 'date' && fields[item.field]) {
      fields[item.field] = dayjs(fields[item.field]).format(item.format || 'YYYY-MM-DD')
    }
    else if (item.type === 'daterange' && fields[item.field]) {
      fields[item.field] = [
        dayjs(fields[item.field][0]).format(item.format || 'YYYY-MM-DD'),
        dayjs(fields[item.field][1]).format(item.format || 'YYYY-MM-DD'),
      ]
    }
  })
  emit('search', fields)
}
function resetForm(formEl) {
  if (!formEl) {
    return
  }
  formEl.resetFields()
  formValues.value = {}
  emit('search', JSON.parse(JSON.stringify(formValues.value)))
}
</script>

<template>
  <el-form
    ref="formRef"
    class="search-form flex"
    :model="formValues"
    inline
    :label-width="labelWidth"
    @keyup.native.enter="searchForm(formRef)"
  >
    <div style="flex: 1 1 0%;" class="grid grid-cols-3 gap-3">
      <el-form-item
        v-for="(item, index) in columns"
        :key="item.field"
        :prop="item.field"
        :label="item.label"
        class="flex-center"
      >
        <template v-if="item.type === 'autocomplete'">
          <el-autocomplete
            v-model="formValues[item.field]"
            :placeholder="item.placeholder || '请输入关键字'"
            :trigger-on-focus="item.triggerOnFocus ?? true"
            :fetch-suggestions="item.fetchSuggestions"
            :clearable="item.clearable ?? true"
            :disabled="item.disabled"
            class="!w-full"
            @select="(val) => item.onSelect?.(val)"
          >
            <template v-if="item.customTemplate" #default="{ item }">
              <div>{{ item.value }} - {{ item.name }}</div>
            </template>
          </el-autocomplete>
        </template>
        <template v-if="item.type === 'input'">
          <el-input
            v-model="formValues[item.field]"
            :style="item.style || 'width:100%'"
            :placeholder="item.placeholder || '请输入关键字'"
            :disabled="item.disabled"
            clearable
          />
        </template>
        <template v-if="item.type === 'select'">
          <el-select
            v-model.trim="formValues[item.field]"
            :style="item.style || 'width: 100%'"
            :placeholder="item.placeholder || '请选择'"
            :disabled="item.disabled"
            :filterable="item.filterable || true"
            clearable
          >
            <el-option
              v-for="s in item.options?.data"
              :key="s[item.options?.key || 'value']"
              :label="s[item.options?.label || 'label']"
              :value="s[item.options?.value || 'value']"
            />
          </el-select>
        </template>
        <template v-if="item.type === 'date'">
          <el-date-picker
            v-model.trim="formValues[item.field]"
            :style="item.style || 'width: 100%'"
            :placeholder="item.placeholder || '请选择日期'"
            :disabled="item.disabled"
            :type="item.dateType"
            clearbale
          />
        </template>
        <template v-if="item.type === 'daterange'">
          <el-date-picker
            v-model.trim="formValues[item.field]"
            :style="item.style || 'width: 100%'"
            :range-separator="item.rangeSeparator"
            :disabled="item.disabled"
            type="daterange"
            :format="item.format"
            start-placeholder="开始日期"
            :end-placeholder="结束日期"
            clearable
          />
        </template>
      </el-form-item>
    </div>
    <div style="flex: 0 0 86px;text-align: right;" class="flex">
      <el-divider direction="vertical" class="h-full relative top-[1px]" />
      <div class="space-y-3 ">
        <el-button type="primary" icon="Search" :loading="loading" @click="searchForm(formRef)">
          搜索
        </el-button>
        <el-button v-if="props.isResetButton" icon="Refresh" @click="resetForm(formRef)">
          重置
        </el-button>
      </div>
      <!--      <el-button v-show="columns.length > 3" link type="primary" @click="toggle"> -->
      <!--        <template #icon> -->
      <!--          &lt;!&ndash;              <SvgIcon :name="fold ? 'i-ep:caret-bottom' : 'i-ep:caret-top' " /> &ndash;&gt; -->
      <!--          <div class="transition-transform duration-300"> -->
      <!--            <ArrowUp v-if="!fold" /> -->
      <!--            <ArrowDown v-else /> -->
      <!--          </div> -->
      <!--        </template> -->
      <!--        {{ fold ? t('expand') : t('collapse') }} -->
      <!--      </el-button> -->
    </div>
  </el-form>
</template>

<style scoped lang="scss">
.search-form{
  :deep(.el-form-item__label){
    text-align: left;
  }
  :deep(.el-form--inline ){
    .el-form-item{
      margin-right: 10px;
    }
  }
}
</style>
